//
//  BillChartViewController.swift
//  bill
//
//  Created by RongJI on 2021/1/20.
//

import UIKit
import Charts
import Toast_Swift

class BillChartViewController: UIViewController {
    
    lazy var pieChartView: PieChartView = {
        let pieChartView = PieChartView.init(frame: CGRect.init(x: 0, y: 130, width: ScreenInfo.Width, height: ScreenInfo.Height - 130))
        pieChartView.usePercentValuesEnabled = true
        pieChartView.drawHoleEnabled = false
        pieChartView.legend.enabled = false
        
        return pieChartView
    }()
    
    lazy var barChartView: BarChartView = {
        let barChartView =  BarChartView.init(frame: CGRect.init(x: 0, y: 130, width: ScreenInfo.Width, height: ScreenInfo.Height - 230))
        barChartView.legend.enabled = false
        
        return barChartView
    }()
    
    let chartsBtn : UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.setTitle("显示柱形图", for: .normal)
        btn.setTitle("显示饼图", for: .selected)
        
        return btn
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        self.view.backgroundColor = UIColor.init(hex: "dddddd")
        
        self.chartsBtn.frame = CGRect(x: 0, y: 80, width: 120, height: 30)
        self.chartsBtn.addTarget(self, action: #selector(showChartByType(btn:)), for: .touchUpInside)
        self.view.addSubview(self.chartsBtn)
        
        self.loadBillInfo()
    }
    
    @objc func showChartByType(btn : UIButton) {
        btn.isSelected = !btn.isSelected
        pieChartView.removeFromSuperview()
        barChartView.removeFromSuperview()
        loadBillInfo()
    }
    
    var dateDic:NSMutableDictionary = {
        let dic = NSMutableDictionary.init()
        return dic
    }()
    
    func loadBillInfo() {
        self.view.makeToastActivity(.center)
        //任务队列
        let queue = DispatchQueue(label: "requestHandler")
        //分组
        let group = DispatchGroup()
        //第一个网络请求，查询群信息
        queue.async(group: group) {
            for type in BillOperationManager.instance.billTypeArr! {
                var money:Float = 0
                let sema = DispatchSemaphore(value: 0)
                
                BillOperationManager.instance.getBillsInfoByKey(key: type as! String) { (bills) in
                    for bill in bills {
                        let moneyStr = BillOperationManager.getString(key: "money", bill: bill)
                        money += Float(moneyStr)!
                    }
                    if money > 0{
                        self.dateDic.setValue(money, forKey: type as! String)
                    }
                    sema.signal()
                }
                sema.wait()
            }
        }
        //全部调用完成后回到主线程,再更新UI
        group.notify(queue: DispatchQueue.main, execute: {[weak self] in
            //tableView同时用到了两个请求到返回结果
            if self?.chartsBtn.isSelected == true {
                self?.drawBarChartView()
            }else {
                self?.drawPieChartView()
            }
            self?.view.hideAllToasts(includeActivity: true, clearQueue: true)
        })
    }
    
    func drawPieChartView() {
        view.addSubview(pieChartView)
        
        let titleArr = NSMutableArray.init()
        let moneyArr = NSMutableArray.init()
        
        for key in self.dateDic.allKeys {
            titleArr.add(key)
            moneyArr.add(self.dateDic[key]!)
        }
        
        var yVals = [PieChartDataEntry]();
        for i in 0...titleArr.count-1 {
            let entry = PieChartDataEntry.init(value: Double(moneyArr[i] as! Float), label: titleArr[i] as? String);
            yVals.append(entry);
        }
        
        let dataSet = PieChartDataSet.init(entries: yVals);
        dataSet.colors = [.red,.gray,.blue,.orange,.green,.cyan,.magenta,.purple,.brown];
        //设置名称和数据的位置 都在内就没有折线了哦
        dataSet.xValuePosition = .insideSlice;
        dataSet.yValuePosition = .insideSlice;
        dataSet.sliceSpace = 1;//相邻块的距离
        dataSet.selectionShift = 6.66;//选中放大半径
        
        let data = PieChartData.init(dataSets: [dataSet]);
        data.setValueFormatter(DigitValueFormatter());//格式化值（添加个%）
        pieChartView.data = data;
    }
    
    func drawBarChartView() {
        view.addSubview(barChartView)
        
        let titleArr = NSMutableArray.init()
        let moneyArr = NSMutableArray.init()
        
        for key in self.dateDic.allKeys {
            titleArr.add(key)
            moneyArr.add(self.dateDic[key]!)
        }
        
        barChartView.xAxis.valueFormatter = XValueFormatter.init(arr: titleArr)
        barChartView.xAxis.labelPosition = .bottom
        barChartView.xAxis.labelTextColor = .blue
        
        var dataEntry = [BarChartDataEntry]();
        for i in 0...titleArr.count-1 {
            let entry = BarChartDataEntry(x: Double(i), y: Double(moneyArr[i] as! Float))
            dataEntry.append(entry);
        }
        
        let dataSet = BarChartDataSet.init(entries: dataEntry)
        let charData = BarChartData.init(dataSet: dataSet)
        dataSet.colors = [.red,.gray,.blue,.orange,.green,.cyan,.magenta,.purple,.brown];
        
        barChartView.data = charData;
 
  }
    
    
    func stringForValue(_ value: Double, entry: ChartDataEntry, dataSetIndex: Int, viewPortHandler: ViewPortHandler?) -> String {
        return String.init(format: "%.2f%%", value);
    }
}


class DigitValueFormatter: NSObject, IValueFormatter {
    func stringForValue(_ value: Double, entry: ChartDataEntry, dataSetIndex: Int, viewPortHandler: ViewPortHandler?) -> String {
        let valueWithoutDecimalPart = String(format: "%.2f%%", value)
        return valueWithoutDecimalPart
        
    }
}

class XValueFormatter: NSObject, IAxisValueFormatter {
    
    var arr : NSArray?
    
    init ( arr : NSArray ){
        self.arr = arr
    }
    func stringForValue(_ value: Double, axis: AxisBase?) -> String {
        
        return self.arr?[Int(value)] as! String
    }
}
